package org.atlantis.mongo.index;

import java.util.Date;

import org.atlantis.mongo.MongoFactory;
import org.atlantis.mongo.TrialUtils;

import com.mongodb.BasicDBObject;
import com.mongodb.CommandResult;
import com.mongodb.DBCollection;

public class IndexTrial {

	// 使用最简单的基本索引。索引大小为：70.406MB
	public void baseIndex() {
		DBCollection dbc = MongoFactory.getCollection("trial.indexes");
		long nowTime = System.currentTimeMillis();
		dbc.ensureIndex(new BasicDBObject("name", 1));
		dbc.ensureIndex(new BasicDBObject("atime", 1));
		for (int i = 0; i < 1000000; i++) {
			dbc.insert(new BasicDBObject().append("name", (long) i).append("atime", new Date(nowTime + i)));
		}
		printSize(dbc.getStats());
	}

	// 使用联合索引。索引大小为：45.969MB
	public void compoundIndex() {
		DBCollection dbc = MongoFactory.getCollection("trial.indexes");
		long nowTime = System.currentTimeMillis();
		dbc.ensureIndex(new BasicDBObject().append("name", 1).append("atime", 1));
		for (int i = 0; i < 1000000; i++) {
			dbc.insert(new BasicDBObject().append("name", (long) i).append("atime", new Date(nowTime + i)));
		}
		printSize(dbc.getStats());
	}

	private void printSize(CommandResult cr) {
		String indexSize = TrialUtils.formatSize(cr.getLong("totalIndexSize"));
		System.out.println("indexSize: " + indexSize);
	}

	public static void main(String[] args) {
		IndexTrial trial = new IndexTrial();
		trial.compoundIndex();
	}
}
